package cn.hchaojie.camp.week2.qa;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DemoCP2 {
	public static void main(String[] args) {
		Factory f = new Factory();
		
		ExecutorService executor = Executors.newFixedThreadPool(2);
		executor.execute(new Producer(f));
		executor.execute(new Consumer(f));
		
		executor.shutdown();
	}
	
	static class Producer implements Runnable {
		Factory factory;
		public Producer(Factory f) {
			this.factory = f;
		}

		@Override
		public void run() {
			try {
				while (true) {
					Thread.sleep((long) (Math.random() * 100));
					factory.put();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	static class Consumer implements Runnable {
		Factory factory;
		public Consumer(Factory f) {
			this.factory = f;
		}

		@Override
		public void run() {
			try {
				while (true) {
					Thread.sleep((long) (Math.random() * 100));
					factory.take();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	static class Factory {
		private static final int MAX = 10;
		private List<Integer> eggs = new ArrayList<>();

		private int id = 1;
		
		public synchronized void put() {
			if (eggs.size() >= MAX) {
				System.out.println("MD, 白来一趟，放不下了。。。鸡蛋扔了，走吧！");
				return;
			} 

			System.out.println("哈哈， 卖出去了。#" + id);
			eggs.add(id++);
		}
		
		public synchronized void take() {
			if (eggs.size() <= 0) {
				System.out.println("MD，白来一趟，卖完了。。。今天不吃饭了，走吧！");
				return;
			}
			
			Integer id = eggs.remove(eggs.size() - 1);
			System.err.println("嘿嘿，买到了 #" + id);
		}
	}
}
